package com.ag.wsq.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
/* 
 * hibernate 查询及分页的基本方法
 * @author 王淑其
 */
public class UtilDAO extends HibernateDaoSupport {
	/*
	 * @param cql
	 * @param timeStart
	 * @param timeEnd
	 * 
	 */	
	public List queryCount(final String cql, final String timeStart,
			final String timeEnd) throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(cql);
				if (timeStart != null && timeStart.length() > 0) {
					java.sql.Date begin = java.sql.Date.valueOf(timeStart);
					query.setDate("timeStart", begin);
				}
				if (timeEnd != null && timeEnd.length() > 0) {
					java.sql.Date end = java.sql.Date.valueOf(timeEnd);
					query.setDate("timeEnd", end);
				}
				List list = query.list();
				return list;
			}
		});
	}
	/*
	 * @param hsql
	 * @param timeStart
	 * @param timeEnd
	 * @param firstRow
	 * @param maxRow
	 * 
	 */	
	public List query(final String hsql, final String timeStart,
			final String timeEnd, final int firstRow, final int maxRow)
			throws Exception {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			public Object doInHibernate(Session s) throws HibernateException,
					SQLException {
				Query query = s.createQuery(hsql);
				if (timeStart != null && timeStart.length() > 0) {
					java.sql.Date begin = java.sql.Date.valueOf(timeStart);
					query.setDate("timeStart", begin);
				}
				if (timeEnd != null && timeEnd.length() > 0) {
					java.sql.Date end = java.sql.Date.valueOf(timeEnd);
					query.setDate("timeEnd", end);
				}
				query.setFirstResult(firstRow);
				query.setMaxResults(maxRow);
				List list = query.list();
				return list;
			}
		});
	}
}
